package cn.edu.nuaa.controller;

import cn.edu.nuaa.model.User;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping(value = "/user")
public class UserController {
    @RequestMapping(value = "/login/page")
    public ModelAndView loginPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        modelAndView.addObject("message", "你好，请登陆");
        return modelAndView;
    }

    @RequestMapping(value = "/login/con")
    public ModelAndView loginCon(@ModelAttribute @RequestBody User user, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        if (user != null && user.getUsername() != null && user.getPassword() != null) {
            if (user.getUsername().equals("zhangsan") && user.getPassword().equals("123456")) {
                modelAndView.setViewName("index");
                modelAndView.addObject("user", user);
                session.setAttribute("USER_SESSION", user);
                return modelAndView;
            }
        }
        modelAndView.setViewName("login");
        modelAndView.addObject("message", "登陆失败，用户名或密码错误");
        return modelAndView;
    }

    @RequestMapping(value = "/logout")
    public ModelAndView logout(HttpSession session) {
        session.invalidate();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        modelAndView.addObject("message", "已成功退出登陆");
        return modelAndView;
    }
}
